/**
 * Copyright (c) 2010
 * Bert Young. UESTC. 
 */
 
#ifndef BERT_TIME_H
#define BERT_TIME_H

#include <sys/time.h>
#include <ctime>

class Time
{    
	struct timespec ts;
	
	unsigned long long msecs; //the milliseconds from 1970
	
public:

	Time() 
	{
		this->now();
	}
	Time(const Time &other):msecs(other.msecs)
	{
		ts = other.ts; 
	}

	void now()
	{
		tzset();
		clock_gettime(CLOCK_REALTIME, &ts);
		msecs = ts.tv_sec * 1000L + ts.tv_nsec/1000000L;
	}
	
	unsigned long msec() const { return msecs; }
	
	Time & operator= (const Time & other)
	{
		msecs = other.msecs;
		ts = other.ts;
		return *this;
	}
	
	bool operator< (const Time & r) const
	{
		return this->msecs < r.msecs;
	}
};


class Timer
{
	Time lastchecktime;
	unsigned long interval;//ms

public:

	Timer(long t): interval(t) {  }

	bool operator()(const Time & now)
	{
		if ( now.msec() >= lastchecktime.msec() + interval)
		{
			lastchecktime = now;
			return true;
		}
		else
			return false;
	}

	void setT(unsigned long T)	{	interval = T;	}
};

#endif
